<?php

	/**
	 * Class for extracting data from ACM Digital Library
	 * 
	 * @author Dragan, Evica Ilieva, Daniil Luzin
	 * @date 2012-06-27
	 */
	class AcmApiImplDAO implements RepositoryDAO{
		
		/**
		 * Get Document Object by doi
		 * 
		 * @author Dragan, Daniil Luzin 
		 *
		 * @param String $doi
		 */
		public function searchByDoi($doi) {
			
			
			// Trim the doi to omit the part before "/"
			if (stripos($doi, '/') > 0) $acm_id = trim(substr($doi,stripos($doi, '/')+1));
						
			
			//Connect to the repository
			$conn = new RepositoryConnection();
			
			//The connection a custom Google Search
			$search=$conn->getConnection();
			
			$keyword_separator=";";
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$keywords = array();
			$tmp_pages = "";
			
			
			$document->setMetadata($metadata);
			$document->setFile($file);
			try{
				//Get the result from the Google Search
				$result = $search->cse->listCse($doi, array(
					'cx' => '003464685527199486674:rgmxgh34f6u', // The custom search engine ID to scope this search query.
				));
			} catch (apiServiceException $e) {
			  // Handle exception. You can also catch Exception here.
			  // You can also get the error code from $e->getCode();
			  //echo $e->getCode();
			}
			

			//Get the metadata from the search. 
			// nb! levenshtein function allows 0 symbols to differ
			// Daniil: MODIFICATION BEGIN
			$i = 0;
			$n=$result['queries']['request'][0]['count'];
		
			//while ($result['items'][$i]['pagemap']['metatags'][0]!=null){
			while ($i<$n){
				//echo $result['items'][$i];
				//echo $i;
				$metadata_array = $result['items'][$i]['pagemap']['metatags'][0];
				
				//var_dump($metadata_array);
				if(isset($metadata_array['citation_doi']))
					$doi_search = $metadata_array['citation_doi'];
				
				//echo "DOI=".$doi_search." real doi=".$doi;
				if (levenshtein($doi_search,$doi)==0) {
					// Daniil: MODIFICATION END
					$document->setUid('ACM:'.$acm_id);
					if(isset($metadata_array['citation_title'])){
						$metadata->setTitle($metadata_array['citation_title']);
						$metadata->setTitleAscii(utf8_deaccent($metadata_array['citation_title']));
					}
					if(isset($metadata_array['citation_authors'])){
						$metadata->setAuthors($metadata_array['citation_authors']);
						$metadata->setAutorsAscii(utf8_deaccent($metadata_array['citation_authors']));
					}
					if(isset($metadata_array['citation_journal_title']))
						$metadata->setJournal($metadata_array['citation_journal_title']); 
					if(isset($metadata_array['citation_date']))
						$metadata->setYear(date('Y-m-d',strtotime($metadata_array['citation_date'])));
					if(isset($metadata_array['citation_volume']))
						$metadata->setVolume($metadata_array['citation_volume']);
					if(isset($metadata_array['citation_issue']))
						$metadata->setIssue($metadata_array['citation_issue']);
					if(isset($metadata_array['citation_firstpage']))
						$tmp_pages = $metadata_array['citation_firstpage'];
					if(isset($metadata_array['citation_lastpage']))
						$tmp_pages = $tmp_pages."-".$metadata_array['citation_lastpage'];
					$metadata->setPages($tmp_pages);
					if(isset($metadata_array['citation_publisher']))
						$metadata->setPublisher($metadata_array['citation_publisher']);
					if(isset($metadata_array['citation_doi']))
						$metadata->setDoi($metadata_array['citation_doi']);
					if(isset($metadata_array['citation_pdf_url']))
						$file->setUrl($metadata_array['citation_pdf_url']);
					if(isset($metadata_array['citation_abstract_html_url']))
						$metadata->setUrl($metadata_array['citation_abstract_html_url']);
					
					if(isset($metadata_array['citation_keywords'])){
						$keyword_array = explode($keyword_separator, $metadata_array['citation_keywords']);
						function trim_value(&$value) {
							$value = trim($value);
						}
						array_walk($keyword_array, 'trim_value');
						$i=0;
						foreach ($keyword_array as $k){
							$keyword = new Keyword();
							$keyword->setKeyword($k);
							$keyword->setSelected(true);
							$keywords[$i]=$keyword;
							$i++;
						}
						$metadata->setKeywords($keywords);
					}	
					
					if(isset($metadata_array['citation_affiliation']))
						$metadata->setAffiliation($metadata_array['citation_affiliation']); //not found till now
					if(isset($metadata_array['citation_secondary_title']))
						$metadata->setSecondaryTitle($metadata_array['citation_secondary_title']); //not found till now
					if(isset($metadata_array['citation_editor']))
						$metadata->setEditor($metadata_array['citation_editor']); //not foudn till now
					if(isset($metadata_array['citation_place_published']))
						$metadata->setPlacePublished($metadata_array['citation_place_published']); //not found till now
					if(isset($metadata_array['citation_reference_type']))
						$metadata->setReferenceType($metadata_array['citation_reference_type']); //not found till now
					if(isset($metadata_array['citation_rating']))
						$metadata->setRating($metadata_array['citation_rating']); //not found till now
					$document->setMetadata($metadata);
					$document->setFile($file);
					
					// Daniil: MODIFICATION BEGIN
					
				}
				else
				{
					//throw new Exception('No matching document found by google API');
					//return null;
				}
				$i++;
			}
				// Daniil: MODIFICATION END
			return $document;
		}
				
		
		/**
		 * Deprecated 
		 * 
		 * @author Daniil Luzin
		 */
		public function findDoiByISSN($issn, $title){
			
			return $doi;
		}
		
		/**
		 * Get document by title using google API 
		 * 
		 * @author Daniil Luzin
		 */
		public function searchByTitle($title){
			
			if (!empty($title)) $title = trim($title);
		
			//Connect to the repository
			$conn = new RepositoryConnection();
			
			//The connection a custom Google Search
			$search=$conn->getConnection();
			try{
				//Get the result from the Google Search
				$result = $search->cse->listCse($title, array(
						'cx' => '003464685527199486674:rgmxgh34f6u', // The custom search engine ID to scope this search query.
				));
			} catch (apiServiceException $e) {
					// Handle exception. You can also catch Exception here.
					// You can also get the error code from $e->getCode();
					//echo $e->getCode();
			}
			
			$keyword_separator=";";
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$document->setMetadata($metadata);
			$document->setFile($file);
			$keywords = array();
			$tmp_pages = "";
			
			//Get the metadata from the search. 
			// nb! levenshtein function allows 3 symbols to differ
			$i = 0;
			while ($result['items'][$i]['pagemap']['metatags'][0]!=null){
				
				$metadata_array = $result['items'][$i]['pagemap']['metatags'][0];
				
				$title_search = $metadata_array['citation_title'];
				if (levenshtein(strtolower($title_search), strtolower($title))<3) {
					
					if(isset($metadata_array['citation_title'])){
						$metadata->setTitle($metadata_array['citation_title']);
						$metadata->setTitleAscii(utf8_deaccent($metadata_array['citation_title']));
					}
					if(isset($metadata_array['citation_authors'])){
						$metadata->setAuthors($metadata_array['citation_authors']);
						$metadata->setAutorsAscii(utf8_deaccent($metadata_array['citation_authors']));
					}
					if(isset($metadata_array['citation_journal_title']))
						$metadata->setJournal($metadata_array['citation_journal_title']);
					if(isset($metadata_array['citation_date']))
						$metadata->setYear(date('Y-m-d',strtotime($metadata_array['citation_date'])));
					if(isset($metadata_array['citation_volume']))
						$metadata->setVolume($metadata_array['citation_volume']);
					if(isset($metadata_array['citation_issue']))
						$metadata->setIssue($metadata_array['citation_issue']);
					if(isset($metadata_array['citation_firstpage']))
						$tmp_pages = $metadata_array['citation_firstpage'];
					if(isset($metadata_array['citation_lastpage']))
						$tmp_pages = $tmp_pages."-".$metadata_array['citation_lastpage'];
					$metadata->setPages($tmp_pages);
					if(isset($metadata_array['citation_publisher']))
						$metadata->setPublisher($metadata_array['citation_publisher']);
					if(isset($metadata_array['citation_doi']))
						$metadata->setDoi($metadata_array['citation_doi']);
					if(isset($metadata_array['citation_pdf_url']))
						$file->setUrl($metadata_array['citation_pdf_url']);
					if(isset($metadata_array['citation_abstract_html_url']))
						$metadata->setUrl($metadata_array['citation_abstract_html_url']);
						
					
					if (stripos($metadata_array['citation_doi'], '/') > 0) {
						
						$acm_id = trim(substr($metadata_array['citation_doi'],stripos($metadata_array['citation_doi'], '/')+1));
						//echo "doi=".$acm_id;
						$document->setUid('ACM:'.$acm_id);
					}
					
					
					
					
					if(isset($metadata_array['citation_keywords'])){
						$keyword_array = explode($keyword_separator, $metadata_array['citation_keywords']);
						function trim_value(&$value) {
							$value = trim($value);
						}
						array_walk($keyword_array, 'trim_value');
						$i=0;
						foreach ($keyword_array as $k){
							$keyword = new Keyword();
							$keyword->setKeyword($k);
							$keyword->setSelected(true);
							$keywords[$i]=$keyword;
							$i++;
						}
						$metadata->setKeywords($keywords);
					}
						
					if(isset($metadata_array['citation_affiliation']))
						$metadata->setAffiliation($metadata_array['citation_affiliation']); //not found till now
					if(isset($metadata_array['citation_secondary_title']))
						$metadata->setSecondaryTitle($metadata_array['citation_secondary_title']); //not found till now
					if(isset($metadata_array['citation_editor']))
						$metadata->setEditor($metadata_array['citation_editor']); //not foudn till now
					if(isset($metadata_array['citation_place_published']))
						$metadata->setPlacePublished($metadata_array['citation_place_published']); //not found till now
					if(isset($metadata_array['citation_reference_type']))
						$metadata->setReferenceType($metadata_array['citation_reference_type']); //not found till now
					if(isset($metadata_array['citation_rating']))
						$metadata->setRating($metadata_array['citation_rating']); //not found till now
					$document->setMetadata($metadata);
					$document->setFile($file);
						
					
				}
				else
				{
					//throw new Exception('No matching document found by google API');
					//return null; 
				}
				$i++;
			}
			return $document;

	}
		
		
		
		/**
		 * No implementation for this function for the ACM DL
		 * 
		 * @param String $uid
		 */
		public function searchByUid($uid) {
			
			// Trim the doi to omit the part before "/"
			//if (stripos($doi, '/') > 0) 
				//$acm_id = trim(substr($doi,stripos($doi, '/')+1));
			
				
			//Connect to the repository
			$conn = new RepositoryConnection();
				
			//The connection a custom Google Search
			$search=$conn->getConnection();
				
			$keyword_separator=";";
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$keywords = array();
			$tmp_pages = "";
			$document->setUid('ACM:'.$uid);
				
			$document->setMetadata($metadata);
			$document->setFile($file);
			try{
				//Get the result from the Google Search
				$result = $search->cse->listCse($uid, array(
						'cx' => '003464685527199486674:rgmxgh34f6u', // The custom search engine ID to scope this search query.
				));
			} catch (apiServiceException $e) {
				// Handle exception. You can also catch Exception here.
				// You can also get the error code from $e->getCode();
				//echo $e->getCode();
			}
				
			
			//Get the metadata from the search.
			// nb! levenshtein function allows 0 symbols to differ
			// Daniil: MODIFICATION BEGIN
			$i = 0;
			$n=$result['queries']['request'][0]['count'];
			
			//while ($result['items'][$i]['pagemap']['metatags'][0]!=null){
			while ($i<$n){
				//echo $result['items'][$i];
				//echo $i;
				$metadata_array = $result['items'][$i]['pagemap']['metatags'][0];
			
				//var_dump($metadata_array);
				if(isset($metadata_array['citation_doi']))
					$uid_search = substr($metadata_array['citation_doi'], strpos($metadata_array['citation_doi'],"/")+1);
			
				//echo "DOI=".$doi_search." real doi=".$doi;
				if (levenshtein($uid_search,$uid)==0) {
					// Daniil: MODIFICATION END
			
					if(isset($metadata_array['citation_title'])){
						$metadata->setTitle($metadata_array['citation_title']);
						$metadata->setTitleAscii(utf8_deaccent($metadata_array['citation_title']));
					}
					if(isset($metadata_array['citation_authors'])){
						$metadata->setAuthors($metadata_array['citation_authors']);
						$metadata->setAutorsAscii(utf8_deaccent($metadata_array['citation_authors']));
					}
					if(isset($metadata_array['citation_journal_title']))
						$metadata->setJournal($metadata_array['citation_journal_title']);
					if(isset($metadata_array['citation_date']))
						$metadata->setYear(date('Y-m-d',strtotime($metadata_array['citation_date'])));
					if(isset($metadata_array['citation_volume']))
						$metadata->setVolume($metadata_array['citation_volume']);
					if(isset($metadata_array['citation_issue']))
						$metadata->setIssue($metadata_array['citation_issue']);
					if(isset($metadata_array['citation_firstpage']))
						$tmp_pages = $metadata_array['citation_firstpage'];
					if(isset($metadata_array['citation_lastpage']))
						$tmp_pages = $tmp_pages."-".$metadata_array['citation_lastpage'];
					$metadata->setPages($tmp_pages);
					if(isset($metadata_array['citation_publisher']))
						$metadata->setPublisher($metadata_array['citation_publisher']);
					if(isset($metadata_array['citation_doi']))
						$metadata->setDoi($metadata_array['citation_doi']);
					if(isset($metadata_array['citation_pdf_url']))
						$file->setUrl($metadata_array['citation_pdf_url']);
					if(isset($metadata_array['citation_abstract_html_url']))
						$metadata->setUrl($metadata_array['citation_abstract_html_url']);
						
					if(isset($metadata_array['citation_keywords'])){
						$keyword_array = explode($keyword_separator, $metadata_array['citation_keywords']);
						function trim_value(&$value) {
							$value = trim($value);
						}
						array_walk($keyword_array, 'trim_value');
						$i=0;
						foreach ($keyword_array as $k){
							$keyword = new Keyword();
							$keyword->setKeyword($k);
							$keyword->setSelected(true);
							$keywords[$i]=$keyword;
							$i++;
						}
						$metadata->setKeywords($keywords);
					}
						
					if(isset($metadata_array['citation_affiliation']))
						$metadata->setAffiliation($metadata_array['citation_affiliation']); //not found till now
					if(isset($metadata_array['citation_secondary_title']))
						$metadata->setSecondaryTitle($metadata_array['citation_secondary_title']); //not found till now
					if(isset($metadata_array['citation_editor']))
						$metadata->setEditor($metadata_array['citation_editor']); //not foudn till now
					if(isset($metadata_array['citation_place_published']))
						$metadata->setPlacePublished($metadata_array['citation_place_published']); //not found till now
					if(isset($metadata_array['citation_reference_type']))
						$metadata->setReferenceType($metadata_array['citation_reference_type']); //not found till now
					if(isset($metadata_array['citation_rating']))
						$metadata->setRating($metadata_array['citation_rating']); //not found till now
					$document->setMetadata($metadata);
					$document->setFile($file);
						
					// Daniil: MODIFICATION BEGIN
						
				}
				else
				{
					//throw new Exception('No matching document found by google API');
					//return null;
				}
				$i++;
			}
			// Daniil: MODIFICATION END
			return $document;
		}
		
		
		private function searchByDoiAcmOld($doi){
			if (!empty($doi)) $doi = trim($doi);
			if (stripos($doi, 'doi:') === 0) $doi = trim(substr($doi, 4));
				
			/* 2012-06-26, Dragan Milchevski: Implementation of Requirement ILF006 Parse a DOI-URL to a readable DOI format*/
			if (stripos($doi, 'http://dx.doi.org/') === 0) $doi = trim(substr($doi, 18));
				
				
			// Trim the doi to omit the part before "/"
			if (stripos($doi, '/') > 0) $acm_id = trim(substr($doi,stripos($doi, '/')+1));
				
				
			$request_url = str_replace('[ACM_ID]', $acm_id, RepositoryConnectionProperty::$_url);
				
			RepositoryConnectionProperty::$_url = $request_url;
				
				
			//Connect to the repository
			$conn = new RepositoryConnection();
				
			//The connection returns a DOM from the URL for the HTML page and
			$html=$conn->getConnection();
				
				
			$metaArray =  array();
			foreach($html->find('head') as $element)
				foreach($element->find('meta') as $meta)
				array_push($metaArray, $meta->attr);
				
				
			$keyword_separator=";";
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$keywords = array();
			$tmp_pages = "";
				
			//Go through the DOM tree and find the attribyte name of the array
			foreach($metaArray as $arr){
				if(isset($arr['name']))
					switch($arr['name']){
						case "citation_title":
							$metadata->setTitle($arr['content']);
							$metadata->setTitleAscii(utf8_deaccent($arr['content']));
							break;
						case "citation_authors":
							$metadata->setAuthors($arr['content']);
							$metadata->setAutorsAscii(utf8_deaccent($arr['content']));
							break;
						case "citation_affiliation":
							$metadata->setAffiliation($arr['content']); //not found till now
							break;
						case "citation_journal":
							$metadata->setJournal($arr['content']); //not found till now
							break;
						case "citation_secondary_title":
							$metadata->setSecondaryTitle($arr['content']); //not found till now
							break;
						case "citation_date":
							$metadata->setYear(date('Y-m-d',strtotime($arr['content'])));
							break;
						case "citation_volume":
							$metadata->setVolume($arr['content']); //not found till now
							break;
						case "citation_issue":
							$metadata->setIssue($arr['content']); //not found till now
							break;
						case "citation_firstpage":
							$tmp_pages = $arr['content'];
							$metadata->setPages($tmp_pages);
							break;
						case "citation_lastpage":
							if(isset($tmp_pages))
								$tmp_pages = $tmp_pages."-".$arr['content'];
							else $tmp_pages = $arr['content'];
							$metadata->setPages($tmp_pages);
							break;
						case "citation_editor":
							$metadata->setEditor($arr['content']); //not foudn till now
							break;
						case "citation_publisher":
							$metadata->setPublisher($arr['content']);
							break;
						case "citation_published":
							$metadata->setPlacePublished($arr['content']); //not found till now
							break;
						case "citation_reference_type":
							$metadata->setReferenceType($arr['content']); //not found till now
							break;
						case "citation_doi":
							$metadata->setDoi($arr['content']);
							break;
						case "citation_pdf_url":
							$file->setUrl($arr['content']);
							break;
						case "citation_rating":
							$metadata->setRating($arr['content']); //not found till now
							break;
						case "citation_abstract_html_url":
							$metadata->setUrl($arr['content']);
							break;
						case "citation_keywords":
							$keyword_array = explode($keyword_separator, $arr['content']);
							function trim_value(&$value) {
								$value = trim($value);
							}
							array_walk($keyword_array, 'trim_value');
							$i=0;
							foreach ($keyword_array as $k){
								$keyword = new Keyword();
								$keyword->setKeyword($k);
								$keyword->setSelected(true);
								$keywords[$i]=$keyword;
								$i++;
							}
							$metadata->setKeywords($keywords);
				}
					
			}
				
			//find the absctract
			$e = $html->find('div.flatbody p div',0);
			$metadata->setAbstract($e->innertext);
			$metadata->setAbstractAscii(utf8_deaccent($e->innertext));
				
			$document->setMetadata($metadata);
			$document->setFile($file);
				
			return $document;
		}
	}
?>